// pages/sales/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    selectData: [
      {
        'id': 0,
        'statusName': '综合办'
      },
      {
        'id': 1,
        'statusName': '交接处'
      },
      {
        'id': 2,
        'statusName': '工程部'
      },
      {
        'id': 3,
        'statusName': '已完成'
      }
    ],
    index: '',//选择的下拉列表下标
    ApprovalList: [],//流程审批列表
    name: '',
    status: '',
    isDelivery: '',
    reviewTel: '',
    money: '',
    fan: '',
    door: '',
    tube: '',
    inversion: '',
    transfer: '',
    window: '',
    asterisk: '',
    pack: '', // 打包类目
    brandId: '', // 品牌
    materialId: '', // 型号
    thicknessId: '', // 壁厚
    openId: '', // 开启
    tel: '',
    type: '',
    affiliated: '',
    isDelivery: '',
    isPlacement: '',
    isAudits: '',
    isPay: '',
    createTime: '',
    updateTime: '',
    createTime1: '',
    updateTime1: '',
    pageNum: 1,
    pageSize: 300,
    total: 0,
    isPages: true,
    pageSizeIndex: 3,
    columns: [
      { value: 0, name: 10 },
      { value: 1, name: 50 },
      { value: 2, name: 100 },
      { value: 6, name: 300 },
      { value: 3, name: 500 },
      { value: 4, name: 1000 },
      { value: 5, name: 5000 },
    ],
    admin: '0',
    bigAdmin: 0,
    totalMoney: 0,
    promise: false,
    searchTagList: [],
    allTotal: 0, // 总货款
    allCollection: 0, // 总收款
    allSurplus: 0, // 剩余款
    allFan: 0,  // 开扇数量
    allDoor: 0, // 开门数量
    allTube: 0, // 方管数量
    allInversion: 0, // 内倒数量
    allTransfer: 0, // 转角数量
    allWindow: 0, // 纱窗数量
    nowDate: '',
    active: [5],
    exportShow: false,
    drawer: '', //开单人
    customerName: '', //客户名称
    billingTel: '', // 开单电话
    share: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      bigAdmin: wx.getStorageSync('admin'),
      admin: wx.getStorageSync('admin') == 1 || wx.getStorageSync('subAdmin') == 1 ? 1 : 0,
      share: options?.share
    });
    this.getDate();
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      pageNum: 1,
      pageSize: 300
    });
    this.childComponent = this.selectComponent("#moneySearch");
    this.childComponent.reset();
    this.getDepartmentList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      pageSize: 300,
      pageSizeIndex: 3
    });
    this.childComponent = this.selectComponent("#moneySearch");
    this.childComponent.reset();
    this.getDepartmentList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (!this.data.isPages) return;
    var pages = this.data.pageNum;
    var page = pages + 1;
    this.setData({ pageNum: page });
    this.getApprovalListData();//调用方法
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
        title: `销售数据统计`,
        path: `/pages/sales/index?share=true`
    }
  },

  // 获取待审核列表  传值搜索
  getApprovalListData() {
    wx.showLoading({
      title: '加载中...',
    });
    const { active } = this.data;
    const data = {
      name: this.data.name,
      tel: this.data.tel,
      status: this.data.status,
      isDelivery: this.data.isDelivery,
      reviewTel: this.data.reviewTel,
      money: this.data.money,
      fan: this.data.fan,
      door: this.data.door,
      tube: this.data.tube,
      inversion: this.data.inversion,
      transfer: this.data.transfer,
      window: this.data.window,
      pack: this.data.pack, // 打包类目
      brandId: this.data.brandId, // 品牌
      materialId: this.data.materialId, // 型号
      thicknessId: this.data.thicknessId, // 壁厚
      openId: this.data.openId, // 开启
      type: this.data.type,
      asterisk: this.data.asterisk,
      createTime: this.data.createTime ? this.data.createTime : '',
      updateTime: this.data.updateTime ? this.data.updateTime : '',
      createTime1: this.data.createTime1 ? this.data.createTime1 : '',
      updateTime1: this.data.updateTime1 ? this.data.updateTime1 : '',
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      affiliated: this.data.affiliated,
      isPlacement: active.includes(0) ? 0 : active.includes(1) ? 1 : '',
      sign1: active.includes(2) ? 0 : active.includes(3) ? 1 : '',
    }
    wx.request({
      url: `${app.globalData.baseUrl}/api/finance/selDeptAll`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      data: data,
      success: (res) => {
        if (res.data.code != 0) return;
        let list = this.data.pageNum == 1 ? res.data.rows : this.quchong([...this.data.ApprovalList, ...res.data.rows]);
        const allList = JSON.parse(JSON.stringify(this.data.pageNum == 1 ? res.data.rows : this.quchong([...this.data.allList, ...res.data.rows])));
        let flag = true;
        if (allList.length >= res.data.total) {
          flag = false;
        }
        let num = 0,
          allTotal = 0,
          allCollection = 0,
          allSurplus = 0,
          allFan = 0,
          allDoor = 0,
          allTube = 0,
          allInversion = 0,
          allTransfer = 0,
          allWindow = 0;
        if (active.includes(4)) list = list.filter(item => (parseFloat(item.total || 0) + parseFloat(item.changeTotal || 0) - parseFloat(item.paid || 0)) > 0);
        list.forEach(item => {
          num += parseFloat(item.money);
          item.surplus = (parseFloat(item.total || 0) + parseFloat(item.changeTotal || 0) - parseFloat(item.paid || 0)).toFixed(2) || 0;
          allTotal = allTotal + parseFloat(item.total) + parseFloat(item.changeTotal);
          allCollection += parseFloat(item.paid);
          allSurplus += parseFloat(item.surplus);
          allFan += parseFloat(item.fan * 100);
          allDoor += parseFloat(item.door * 100);
          allTube += parseFloat(item.tube * 100);
          allInversion += parseFloat(item.inversion * 100);
          allTransfer += parseFloat(item.transfer * 100);
          allWindow += parseFloat(item.window * 100);
          item.totalShow = (parseFloat(item.total) + parseFloat(item.changeTotal)).toFixed(2);
          item.isOpen = true;
        });
        this.setData({
          allList,
          ApprovalList: list,
          isPages: flag,
          totalMoney: num,
          allTotal: allTotal.toFixed(2), // 总货款
          allCollection: allCollection.toFixed(2), // 总收款
          allSurplus: allSurplus.toFixed(2), // 剩余款
          allFan: allFan > 0 ? (allFan / 100).toFixed(2) : '',  // 开扇数量
          allDoor: allDoor > 0 ? (allDoor / 100).toFixed(2) : '', // 开门数量
          allTube: allTube > 0 ? (allTube / 100).toFixed(2) : '', // 方管数量
          allInversion: allInversion > 0 ? (allInversion / 100).toFixed(2) : '', // 内倒数量
          allTransfer: allTransfer > 0 ? (allTransfer / 100).toFixed(2) : '', // 转角数量
          allWindow: allWindow > 0 ? (allWindow / 100).toFixed(2) : '', // 纱窗数量
        });
        wx.hideLoading();
      }
    })
  },

  // 数据去重
  quchong(arr) {
    console.log(arr.length)
    var tempArr = []; //返回的值
    var indexArr = []; //返回的索引
    for (var i = 0; i < arr.length; i++) {
      if (tempArr.indexOf(arr[i]) == -1) {
        tempArr.push(arr[i]);
        indexArr.push(i)
      } else if (tempArr.indexOf(arr[i]) >= 0) {
        for (var j = 0; j < tempArr.length; j++) {
          if (tempArr[j] == arr[i]) {
            tempArr.splice(j, 1, tempArr[j]);
            indexArr.splice(j, 1, i);
          }
        }
      }
    }
    return tempArr
  },

  toDetail(e) {
    let id = e.currentTarget.dataset.id;
    // TOO  添加财务工单页面
    wx.navigateTo({
      url: `/pages/financialDetails/index?id=${id}&status=${this.data.currentTab}&sale=1`
    })
  },

  onSelectPageSize(e) {
    this.setData({
      pageSizeIndex: e.detail.value,
      pageNum: 1,
      pageSize: this.data.columns[e.detail.value].name,
      isPages: true,
    });
    this.getApprovalListData();
  },

  onDisplay() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },

  search(e) {
    const form = e.detail.form;
    const nameObj = e.detail.nameObj;
    this.setData({
      ...form,
      pageNum: 1,
      show: false,
    });
    this.getApprovalListData();
    const arr = [];
    if (form.name) arr.push(`详细地址:${form.name}`);
    if (form.tel) arr.push(`联系电话:${form.tel}`);
    if (form.type) arr.push(`项目加工形态:${form.type}`);
    if (form.money) arr.push(`装修数量:${form.money}`);
    if (form.reviewTel) arr.push(`发起人和电话:${form.reviewTel}`);
    if (form.fan) arr.push(`开扇数量:${form.fan}`);
    if (form.door) arr.push(`开门数量:${form.door}`);
    if (form.tube) arr.push(`方管数量:${form.tube}`);
    if (form.inversion) arr.push(`内倒数量:${form.inversion}`);
    if (form.transfer) arr.push(`转角数量:${form.transfer}`);
    if (form.window) arr.push(`开扇纱窗数量:${form.window}`);
    if (nameObj.packName) arr.push(`打包类目:${nameObj.packName}`);
    if (nameObj.brandName) arr.push(`品牌:${nameObj.brandName}`);
    if (nameObj.materialName) arr.push(`型号:${nameObj.materialName}`);
    if (nameObj.thicknessName) arr.push(`壁厚:${nameObj.thicknessName}`);
    if (nameObj.openName) arr.push(`开启:${nameObj.openName}`);
    if (nameObj.typeName) arr.push(`部门:${nameObj.typeName}`);
    if (nameObj.deliveryName) arr.push(`是否交付:${nameObj.deliveryName}`);
    if (nameObj.affiliatName) arr.push(`隶属归类：${nameObj.affiliatName}`)
    if (form.createTime1) arr.push(`创建时间:${form.createTime1} - ${form.updateTime1}`);
    if (form.createTime) arr.push(`更新时间:${form.createTime} - ${form.updateTime}`);
    if (nameObj.asteriskName) arr.push(`星星状态：${nameObj.asteriskName}`);
    this.setData({ searchTagList: arr });
  },

  updateId(id, list) {
    let name = '';
    list.forEach(item => {
      if (id == item.dictCode) name = item.dictLabel;
    })
    return name;
  },

  resetIsPage() {
    this.setData({ isPages: true });
  },

  // 获取部门列表
  getDepartmentList() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/finance/getUserDept`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          const deptIds = [];
          res?.data?.data?.forEach(item => {
            deptIds.push(item.deptId);
          });
          this.setData({ promise: deptIds.indexOf(3) > -1 });
        }
      }
    })
  },

  isPlacementTab(e) {
    let { active } = this.data;
    if (e.currentTarget.dataset.id === 0) {
      if (active.includes(0)) { active = active.filter(item => item !== 0 && item !== 1 && item !== 5); console.log(active); }
      else { active = active.filter(item => item !== 1 && item !== 5); active.push(0); }
      this.setData({ active });
    } else if (e.currentTarget.dataset.id === 1) {
      if (active.includes(1)) { active = active.filter(item => item !== 0 && item !== 1 && item !== 5); }
      else { active = active.filter(item => item !== 0 && item !== 5); active.push(1); }
      this.setData({ active });
    } else if (e.currentTarget.dataset.id === 2) {
      if (active.includes(2)) { active = active.filter(item => item !== 2 && item !== 3 && item !== 5); }
      else { active = active.filter(item => item !== 3 && item !== 5); active.push(2); }
      this.setData({ active });
    } else if (e.currentTarget.dataset.id === 3) {
      if (active.includes(3)) { active = active.filter(item => item !== 2 && item !== 3 && item !== 5); }
      else { active = active.filter(item => item !== 2 && item !== 5); active.push(3); }
      this.setData({ active });
    } else if (e.currentTarget.dataset.id === 4) {
      if (active.includes(4)) { active = active.filter(item => item !== 4 && item != 5); }
      else { active.push(4); }
      this.setData({ active });
    }
    if (e.currentTarget.dataset.id === 5 || this.data.active.length === 0) {
      this.setData({ active: [5] });
    }
    this.getApprovalListData();
  },

  clearSearch() {
    this.setData({ searchTagList: [] });
    this.childComponent = this.selectComponent("#moneySearch");
    this.childComponent.reset();
  },

  getDate() {
    let date = new Date();
    // 获取年份
    let year = date.getFullYear();
    // 获取月份，注意月份是从0开始的，所以需要加1
    let month = date.getMonth() + 1;
    // 获取日期
    let day = date.getDate();
    // 格式化月份、日期、分钟和秒数，如果小于10则在前面补0
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;

    // 组合成需要的格式
    const formattedDate = `${year}-${month}-${day}`;
    this.setData({ nowDate: formattedDate });
  },

  onExportShow() {
    this.setData({ exportShow: true });
  },

  onExportClose() {
    this.setData({
      exportShow: false
    });
  },

  panel(e) {
    const arr = this.data.ApprovalList;
    arr.forEach(item => {
      if (e.currentTarget.dataset.id == item.id) item.isOpen = !item.isOpen;
    });
    this.setData({ ApprovalList: arr })
  },

  onExport(e) {
    const { active, name, tel, status, isDelivery, reviewTel, money, fan, door, tube, inversion, transfer, window, pack, brandId, materialId, thicknessId, openId, type, createTime, updateTime, createTime1, updateTime1, affiliated, drawer, customerName, billingTel, asterisk, pageNum, pageSize } = this.data;
    // if (!customerName) {
    //   Toast("请输入客户名称");
    //   return;
    // }
    // if (!billingTel) {
    //   Toast("请输入电话");
    //   return;
    // }
    // if (!drawer) {
    //   Toast("请输入开单人");
    //   return;
    // }
    wx.showLoading({
      title: '导出中...',
    });
    const data = {
      name,
      tel,
      status,
      isDelivery,
      reviewTel,
      money,
      // fan,
      // door,
      // tube,
      // inversion,
      // transfer,
      // window,
      // pack, // 打包类目
      // brandId, // 品牌
      // materialId, // 型号
      // thicknessId, // 壁厚
      // openId, // 开启
      // type,
      asterisk,
      createTime: createTime ? createTime : '',
      updateTime: updateTime ? updateTime : '',
      createTime1: createTime1 ? createTime1 : '',
      updateTime1: updateTime1 ? updateTime1 : '',
      affiliated,
      isPlacement: active.includes(0) ? 0 : active.includes(1) ? 1 : '',
      sign1: active.includes(2) ? 0 : active.includes(3) ? 1 : '',
      // drawer,
      // customerName,
      // billingTel,
      pageNum: 1,
      pageSize: pageSize * pageNum,
    }
    const that = this;
    const types = e.currentTarget.dataset.type;
    wx.request({
      url: `${app.globalData.baseUrl}${types == 'docx' ? '/api/finance/selDeptAllWord' : '/api/finance/selDeptAllExport'}`,
      method: "POST",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data,
      success: (res) => {
        if (res.data.code == 0) {
          const url = types == 'docx' ? res.data.msg : `${app.globalData.baseUrl}/common/download?fileName=${encodeURI(res.data.msg)}`;
          that.onExportClose();
          wx.getSystemInfo({
            success: function (result) {
              if (result.platform === 'ios' || result.platform === 'android') {
                that.saveMobile(url, types);
              } else if (result.platform === 'windows' || result.platform === 'mac') {
                that.savePc(url, types);
              }
            }
          });
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '出错啦',
        })
      }
    })
  },

  savePc(url, fileType) {
    wx.request({
      url: url,
      responseType: 'arraybuffer', // 设置响应类型为arraybuffer以接收二进制数据
      success: (res) => {
        // 获取文件名
        const fileName = fileType == 'docx' ? url.split('/').pop() : url.split('=').pop();

        // 写入文件
        wx.getFileSystemManager().writeFile({
          filePath: wx.env.USER_DATA_PATH + '/' + fileName, // 指定要写入的文件路径
          data: res.data, // 文件内容
          encoding: 'binary', // 指定文件编码
          success: (writeRes) => {
            console.log('文件保存成功', writeRes);
            // 这里可以调用wx.saveFileToDisk将文件保存到用户电脑
            wx.saveFileToDisk({
              filePath: wx.env.USER_DATA_PATH + '/' + fileName,
              success: (saveRes) => {
                wx.showToast({
                  title: '文件保存成功',
                });
              },
              fail: (error) => {
                console.error('文件保存到电脑失败', error);
              }
            });
          },
          fail: (error) => {
            console.error('文件保存失败', error);
          }
        });
      },
      fail: (error) => {
        console.error('文件下载失败', error);
      }
    });
  },

  saveMobile(url, fileType) {
    wx.downloadFile({
      url,
      success(res) {
        if (res.statusCode === 200) {
          wx.openDocument({
            filePath: res.tempFilePath,
            showMenu: true,
            fileType
          });
        }
      }
    })
  },

  resetExport() {
    this.setData({
      drawer: '', //开单人
      customerName: '', //客户名称
      billingTel: '', // 开单电话
    });
  },
})